import { Schema } from './schema';
import { Rule, Tree, noop } from '@angular-devkit/schematics';
import { getProjectFromWorkspace } from '@angular/cdk/schematics';
import { getWorkspace } from '@schematics/angular/utility/workspace';
import { WorkspaceDefinition } from '@angular-devkit/core/src/workspace';
import { existsSync } from 'fs';

const appComponentContent = `import { Component } from '@angular/core';
import { ReplaceableComponentsService } from '@abp/ng.core';
import { eThemeBasicComponents } from '@abp/ng.theme.basic';

import { JoyApplicationLayoutComponent } from 'joy-abpui-angular';

@Component({
  selector: 'app-root',
  template: \`
    <abp-loader-bar></abp-loader-bar>
    <abp-dynamic-layout></abp-dynamic-layout>
  \`,
})
export class AppComponent {
  constructor(private replaceableComponents: ReplaceableComponentsService) {
    this.replaceableComponents.add({
      component: JoyApplicationLayoutComponent,
      key: eThemeBasicComponents.ApplicationLayout,
    });
  }
}
`;

export function updateAppComponent(options: Schema): Rule {
  return async (host: Tree) => {
    const workspace = (await getWorkspace(host)) as unknown as WorkspaceDefinition;
    const project = getProjectFromWorkspace(workspace, options.project);
    const appComponentFile = `${project.sourceRoot}/app/app.component.ts`;
    if (existsSync(appComponentFile)) {
      host.overwrite(appComponentFile, appComponentContent);
    } else {
      host.create(appComponentFile, appComponentContent);
    }

    return noop();
  };
}
